import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ApiService extends GetConnect {
  ApiService(String baseUrl) {
    httpClient.baseUrl = baseUrl;
    onInit();
  }

  @override
  void onInit() {
    super.onInit();
    // 超时时间
    httpClient.timeout = Duration(seconds: 10);

    //请求拦截器
    httpClient.addRequestModifier<dynamic>((request) async {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString('token');
      if (token != null) {
        request.headers['Authorization'] = 'Bearer $token';
        request.headers['token'] = token;
      }
      return request;
    });

    //响应拦截器
    httpClient.addResponseModifier((request, response) {
      return response;
    });

    // 认证拦截器
    httpClient.addAuthenticator<dynamic>((request) async {
      return request;
    });
  }

  // get请求
  Future<dynamic> getRequest(String path) async {
    final response = await get(path);
    if (response.status.hasError) {
      print("发送失败：${response.statusText}");
      return null;
    } else {
      print("发送成功 ：${response.body}");
    }
      return response.body;
  }

  // post请求
  Future<dynamic> postRequest(String path, Map<String,dynamic> data) async {
    final response = await post(path, data);
    if (response.status.hasError) {
      print("发送失败：${response.statusText}");
      return null;
    } else {
      print("发送成功 ：${response.body}");
    }
    return response.body;
  }

  // put请求
  Future<dynamic> putRequest(String path, Map<String,dynamic> data) async {
    final response = await put(path, data);
    if (response.status.hasError) {
      print("发送失败：${response.statusText}");
      return null;
    }else {
      print("发送成功 ：${response.body}");
    }
    return response.body;
  }

  // delete请求
  Future<dynamic> deleteRequest(String path) async {
    final response = await delete(path);
    if (response.status.hasError) {
      print("发送失败：${response.statusText}");
      return null;
    } else {
      print("发送成功 ：${response.body}");
    }
    return response.body;
  }
}
